<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    :maskClosable="false"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :replaceFields="{ title: 'title', key: 'id' }"
          @check="onCheck"
          checkable
          toolbar
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './group.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';

  import { getAuleList, GroupAdd, GroupEdit } from '/@/api/demo/auth';

  export default defineComponent({
    name: 'GroupDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);
      const childNodes = ref([]);
      const halfCheckedKeys = ref([]);

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          treeData.value = (await getAuleList()) as any as TreeItem[];
        }
        isUpdate.value = !!data?.isUpdate;
        
        childNodes.value = [];
        halfCheckedKeys.value = [];
        
        if (unref(isUpdate)) {
          getChildNodes(treeData.value);
          //console.log(childNodes.value);
          let rulesArr = uniqueTree(data.record.rules);
          console.log(rulesArr);
          console.log(halfCheckedKeys.value);

          setFieldsValue({
            ...data.record,
          });
          setFieldsValue({ rules: rulesArr });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      function onCheck(checkedKeys, e) {
        //console.log('checkedKeys', checkedKeys);
        //console.log('e', e);
        //注意：halfCheckedKeys 是没有全部勾选状态下的父节点
        halfCheckedKeys.value = e.halfCheckedKeys;
        console.log(halfCheckedKeys.value);
      }

      function getChildNodes(data) {
        let arr = [];
        data &&
          data.map((item) => {
            if (item.children && item.children.length > 0) {
              return getChildNodes(item.children);
            } else {
              childNodes.value.push(item.id);
            }
          });
      }

      function uniqueTree(rules) {
        let uniqueChild = [];
        let arr = childNodes.value;
        for (var i in arr) {
          for (var k in rules) {
            if (rules[k] === arr[i]) {
              uniqueChild.push(rules[k]);
            }
          }
        }
        for (var i in rules) {
          if (uniqueChild.indexOf(rules[i]) === -1) {
            halfCheckedKeys.value.push(rules[i]);
          }
        }
        return uniqueChild;
      }

      async function handleSubmit() {
        try {
          const values = await validate();
          values.rules = [...new Set(values.rules.concat(halfCheckedKeys.value))];
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          if (!unref(isUpdate)) {
            await GroupAdd({ ...values });
          } else {
            await GroupEdit({ ...values });
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        onCheck,
        getTitle,
        handleSubmit,
        treeData,
      };
    },
  });
</script>
